package top.jnaw.jee.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.message.BasicHttpResponse;

/**
 * Created by neo on 17-6-1.
 *
 * HTTP 请求工具类
 */
public class Https {

  /**
   * 未授权：401
   */
  public static final int CODE_UNAUTHORIZED = HttpURLConnection.HTTP_UNAUTHORIZED;

  /**
   * 找不到：404
   */
  public static final int CODE_NOT_FOUND = HttpURLConnection.HTTP_NOT_FOUND;

  /**
   * 不可接受的参数：406
   */
  public static final int CODE_NOT_ACCEPTABLE = HttpURLConnection.HTTP_NOT_ACCEPTABLE;

  /**
   * 请求冲突：409
   */
  public static final int CODE_CONFLICT = HttpURLConnection.HTTP_CONFLICT;

  private static final MediaType JSON = MediaType
      .parse("application/json; chartset=utf-8");
  private static OkHttpClient CLIENT = new OkHttpClient();

  /**
   * 发送 GET 请求
   */
  public static String get(String url) {
    String result = null;

    try {
      final Request request = new Request.Builder().url(url).build();
      final Response response = CLIENT.newCall(request).execute();
      result = response.body().string();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }

  public static File getFile(String url, String path) {
    File file = null;

    try {
      final Request request = new Request.Builder().url(url).build();
      final Response response = CLIENT.newCall(request).execute();
      if (response.isSuccessful() && !response.body().contentType().toString()
          .contains("text")) {
        file = new File(path);

        BufferedOutputStream out = new BufferedOutputStream(
            new FileOutputStream(file));
        out.write(response.body().bytes());
        out.close();

        return file;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return file;
  }

  /**
   * 发送 POST 请求
   *
   * @param param key=value
   */
  public static String post(String url, String param) {
    String result = null;

    try {
      final RequestBody body = RequestBody.create(JSON, param);
      final Request request = new Request.Builder().url(url).post(body).build();
      final Response response = CLIENT.newCall(request).execute();
      result = response.body().string();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }

  /**
   * 发送 POST 请求
   *
   * @param url 请求的url
   * @param headers headers
   * @param params params
   */
  public static String post(String url, Map<String, String> headers,
      Map<String, String> params) {
    String result = null;

    try {
      Request.Builder builder = new Request.Builder().url(url);

      for (Map.Entry<String, String> entry : headers.entrySet()) {
        builder.addHeader(entry.getKey(), entry.getValue());
      }

      FormBody.Builder body = new FormBody.Builder();
      for (Map.Entry<String, String> entry : params.entrySet()) {
        body.add(entry.getKey(), entry.getValue());
      }

      final Request request = builder.post(body.build()).build();
      final Response response = CLIENT.newCall(request).execute();
      result = response.body().string();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

  public static HttpResponse getRawHtml(HttpClient client, String personalUrl) {
    //获取响应文件，即html，采用get方法获取响应数据
    HttpGet getMethod = new HttpGet(personalUrl);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
        HttpStatus.SC_OK, "OK");
    try {
      //执行get方法
      response = client.execute(getMethod);
    } catch (IOException e) {
      e.printStackTrace();

    } finally {
      // getMethod.abort();
    }
    return response;
  }
}
